<template>
  <div id="ruleDetailPage">
    <!-- 麵包屑導航 -->
    <BreadcrumbComponent :breadcrumbItems="breadcrumbItems" />

    <!-- 消息詳情卡片 -->
    <a-space direction="vertical" style="width: 100%">
      <a-card title="基本參數" class="detail-card" :loading="loading">
        <template v-if="!loading && !rule.id">
          <a-empty description="數據加載失敗，請重試" />
        </template>
        <template v-else>
          <a-descriptions bordered>
            <a-descriptions-item label="規則名稱">
              {{ rule.name }}
            </a-descriptions-item>

            <a-descriptions-item label="員工類型">
              <template v-if="rule.staffType === 1"> 合作人 </template>
              <template v-else-if="rule.staffType === 2"> 員工 </template>
              <template v-else> 未知 </template>
            </a-descriptions-item>
            <a-descriptions-item label="駐診形式">
              <template v-if="rule.shiftType === 1"> 全日 </template>
              <template v-else-if="rule.shiftType === 2"> 半日 </template>
              <template v-else> 未知 </template>
            </a-descriptions-item>
            <a-descriptions-item label="全部醫師">
              <template v-if="rule.allDoctor === 1"> 是 </template>
              <template v-else-if="rule.allDoctor === 0"> 否 </template>
              <template v-else> 未知 </template>
            </a-descriptions-item>
            <a-descriptions-item label="銷售額不計診金">
              <template v-if="rule.salesNoConsult === 1"> 是 </template>
              <template v-else-if="rule.salesNoConsult === 0"> 否 </template>
              <template v-else> 未知 </template>
            </a-descriptions-item>
            <a-descriptions-item label="規則類型">
              <template v-if="rule.ruleType === 1"> 跳級 </template>
              <template v-else-if="rule.ruleType === 2"> 累進 </template>
              <template v-else> 未知 </template>
            </a-descriptions-item>
            <a-descriptions-item label="生效日期">
              {{ rule.validFrom }}
            </a-descriptions-item>
            <a-descriptions-item label="失效日期">
              {{ rule.validTo }}
            </a-descriptions-item>
            <a-descriptions-item label="修改人">{{
              rule.updatedBy
            }}</a-descriptions-item>
            <a-descriptions-item label="更新時間">{{
              $formatDate(rule.updatedAt)
            }}</a-descriptions-item>
          </a-descriptions>
        </template>
      </a-card>
      <!-- 添加 -->
      <a-space>
        <a-button type="primary" @click="handleCreate">
          <template #icon>
            <PlusOutlined />
          </template>
          新建項
        </a-button>
      </a-space>

      <a-table
        :dataSource="rule.items"
        :columns="ruleItemColumns"
        :loading="loading"
        :pagination="false"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'updatedAt'">
            {{ $formatDate(record.updatedAt) }}
          </template>
          <template v-if="column.key === 'action'">
            <a-button @click="handleEdit(record)">修改</a-button>
            <a-button danger @click="handleDelete(record)">刪除</a-button>
          </template>
        </template>
      </a-table>

      <!-- 適用醫師名單 -->
      <a-card title="適用醫師名單" v-if="rule.allDoctor === 0">
        <template #extra>
          <a-button
            type="primary"
            size="small"
            shape="round"
            @click="handleOpenDrawer"
          >
            設置名單
          </a-button>
        </template>
        <a-row :gutter="16" :wrap="true">
          <a-col
            :span="4"
            v-for="doctor in applicableDoctors"
            :key="doctor.key"
          >
            {{ doctor.label }}
          </a-col>
        </a-row>
      </a-card>

      <BackButton />
    </a-space>
    <a-modal v-model:open="showModalCreate" title="新建規則項" :footer="null">
      <DynamicForm
        ref="createFormRef"
        :fieldConfig="createFieldConfig"
        @submit="handleCreateSubmit"
      />
    </a-modal>
    <a-modal v-model:open="showModalEdit" :footer="null">
      <template #title>
        編輯規則項
        <a-tag color="warning"
          ><template #icon>
            <ExclamationCircleOutlined />
          </template>
          ID: {{ editFormData.id }}</a-tag
        >
      </template>
      <DynamicForm
        ref="editFormRef"
        :fieldConfig="editFieldConfig"
        :formData="editFormData"
        @submit="handleEditSubmit"
      />
    </a-modal>

    <!-- 批量設置抽屜 -->
    <a-drawer
      title="設置使用醫師名單"
      :width="720"
      :open="showDrawer"
      @close="showDrawer = false"
    >
      <template #extra>
        <a-space>
          <a-button @click="showDrawer = false">取消</a-button>
          <a-button type="primary" @click="handleBatchSetupSubmit"
            >提交</a-button
          >
        </a-space>
      </template>
      <a-form ref="formRef" :model="formState">
        <a-form-item label="適用醫師">
          <a-checkbox-group
            v-model:value="formState.doctorStaffCodes"
            style="width: 100%; padding-top: 8px"
          >
            <a-row :gutter="16" :wrap="true" style="row-gap: 13px">
              <a-col
                :span="6"
                v-for="option in doctorOptions"
                :key="option.key"
              >
                <a-checkbox :value="option.key">
                  {{ option.label }}
                </a-checkbox>
              </a-col>
            </a-row>
          </a-checkbox-group>
        </a-form-item>
      </a-form>
    </a-drawer>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, reactive } from "vue";
import { ExclamationCircleOutlined, PlusOutlined } from "@ant-design/icons-vue";
import { useRoute } from "vue-router";
import { regularShareRuleApi } from "@/api";
import BreadcrumbComponent from "@/components/BreadcrumbComponent.vue";
import {
  getCreteFieldConfig,
  getEditFieldConfig,
  getTableColumns,
} from "@/models/regularShareItem";
import { message, Modal } from "ant-design-vue";
import BackButton from "@/components/BackButton.vue";
import DynamicForm from "@/components/DynamicForm.vue";
import { useDoctorStore } from "@/store/doctorStore";

const route = useRoute();

// 麵包屑導航
const breadcrumbItems = [
  { url: "/regular", name: "附加推廣分成規則" },
  { url: "", name: "規則詳情" },
];

// 詳情數據
const rule = reactive({
  id: 0,
  name: "",
  staffType: 0,
  shiftType: 0,
  ruleType: 0,
  salesNoConsult: 0,
  doctorStaffCodes: [],
  allDoctor: 0,
  validFrom: "",
  validTo: "",
  items: [],
  updatedBy: "",
  updatedAt: "",
});
const loading = ref(true);
const ruleId = Number(route.params.id);
const applicableDoctors = ref([]);
const ruleItemColumns = ref([]);

// 獲取詳情
const fetchDetail = async () => {
  try {
    const { data } = await regularShareRuleApi.getRegularShareRuleDetail(
      ruleId
    );
    Object.assign(rule, data);
    ruleItemColumns.value = getTableColumns(rule.ruleType);
    doctorOptions.value = await doctorStore.fetchOptionsByStaffType(
      rule.staffType
    );
    applicableDoctors.value = doctorOptions.value.filter((item) =>
      rule.doctorStaffCodes.includes(item.key)
    );
  } catch (error) {
    console.error("獲取詳情失敗", error);
  } finally {
    loading.value = false;
  }
};

// 初始化加載
onMounted(async () => {
  await fetchDetail();
});

// 新建
const createFieldConfig = ref<Record<string, any>>({});
const showModalCreate = ref(false);
const createFormRef = ref();

const handleCreate = () => {
  if (Object.keys(createFieldConfig.value).length === 0) {
    createFieldConfig.value = getCreteFieldConfig(rule.ruleType);
  }
  showModalCreate.value = true;
};
const handleCreateSubmit = async (data: any) => {
  try {
    const { salesRange, ...rest } = data;
    const createData = {
      ...rest,
      lowerLimit: salesRange[0] ?? 0,
      upperLimit: salesRange[1] ?? 0,
    };
    await regularShareRuleApi.createRegularShareRuleItem(ruleId, createData);
    message.success("創建規則項成功");
    showModalCreate.value = false;
    createFormRef.value?.resetForm();
    fetchDetail();
  } catch (error) {
    console.error("創建規則項失敗", error);
  } finally {
    createFormRef.value.resetLoading();
  }
};

// 修改
const editFormData = reactive<any>({});
const editFieldConfig = ref<Record<string, any>>({});
const showModalEdit = ref(false);
const editFormRef = ref();

const handleEdit = (record) => {
  showModalEdit.value = true;
  if (Object.keys(editFieldConfig.value).length === 0) {
    editFieldConfig.value = getEditFieldConfig(rule.ruleType);
  }
  record.salesRange = [record.lowerLimit, record.upperLimit];
  Object.assign(editFormData, record);
};

const handleEditSubmit = async (data: any) => {
  try {
    const { salesRange, ...rest } = data;
    const updateData = {
      ...rest,
      lowerLimit: salesRange[0] ?? 0,
      upperLimit: salesRange[1] ?? 0,
    };
    await regularShareRuleApi.updateRegularShareRuleItem(
      ruleId,
      editFormData.id,
      updateData
    );
    message.success("修改規則項成功");
    showModalEdit.value = false;
    fetchDetail();
  } catch (error) {
    console.error("修改項失敗", error);
  } finally {
    editFormRef.value.resetLoading();
  }
};

const handleDelete = async (record: any) => {
  Modal.confirm({
    title: "確認刪除",
    content: `確定要刪除規則項${record.name} 嗎？`,
    okText: "確定",
    cancelText: "取消",
    onOk: async () => {
      try {
        await regularShareRuleApi.deleteRegularShareRuleItem(ruleId, record.id);
        message.success("刪除規則項成功");
        fetchDetail();
      } catch (error) {
        console.error("刪除規則項失敗:", error);
      }
    },
  });
};

// 批量設置
const showDrawer = ref(false);
const formState = reactive({
  doctorStaffCodes: [],
});
const formRef = ref();

const doctorOptions = ref([]);

const doctorStore = useDoctorStore();

// 打開設置抽屜
const handleOpenDrawer = async () => {
  if (Object.keys(doctorOptions.value).length === 0) {
    doctorOptions.value = await doctorStore.fetchOptionsByStaffType(
      rule.staffType
    );
  }
  formState.doctorStaffCodes = rule.doctorStaffCodes || [];
  showDrawer.value = true;
};

const handleBatchSetupSubmit = async () => {
  try {
    await formRef.value.validate();
    await regularShareRuleApi.setRegularShareRuleDoctor(ruleId, formState);
    message.success("設置醫師成功");
    rule.doctorStaffCodes = formState.doctorStaffCodes;
    applicableDoctors.value = doctorOptions.value.filter((item) =>
      rule.doctorStaffCodes.includes(item.key)
    );
    showDrawer.value = false;
    // fetchDetail()
  } catch (error) {
    console.error("批量設置推廣活動項失敗", error);
  }
};
</script>

<style scoped></style>
